<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!--添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesdialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!--展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row  v-for="(item1, index1) in scope.row.children" :key="item1.id"
                     :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']">
              <!--渲染一级权限 -->
              <el-col :span="5" >
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id"
                        :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                      {{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children" :key="item3.id"
                            type="warning" closable @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--<pre>
              {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <!--索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" @click='showRolesEditDialog(scope.row.id)'>编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click='removeRolesById(scope.row.id)'>删除</el-button>
            <el-button type="warning" icon="el-icon-star-off" @click="showRightsDialog(scope.row)">分配权限</el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesdialogVisible"
      width="50%"
      @close="addRolesDialogClosed">
      <!--内容主体区域 Form表单-->
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域 -->
      <span slot="footer" class="dialog-footer">
		    <el-button @click="addRolesdialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addRoles">确 定</el-button>
		  </span>
    </el-dialog>

    <!--编辑角色 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="editRolesDialogClosed">

      <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editRolesForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
		    <el-button @click="editRolesDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="editRolesInfo">确 定</el-button>
		  </span>
    </el-dialog>


    <!--分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRolesDialogClosed">
      <!--树形控件 -->
      <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defKeys" ref="treeRef"></el-tree>

      <span slot="footer" class="dialog-footer">
		    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRight">确 定</el-button>
		  </span>
    </el-dialog>
  </div>
</template>

<script>
  export default{
    data() {
      return {
        //所有角色列表
        rolesList: [],
        addRolesdialogVisible: false,
        addRolesForm: {
          roleName: '',
          roleDesc: ''
        },
        addRolesFormRules: {
          roleName: [ {required: true, message: '请输入角色名称', trigger: 'blur'} ],
          roleDesc: [ {required: true, message: '请输入角色描述', trigger: 'blur'} ]
        },

        editRolesDialogVisible: false,
        editRolesForm: {},
        editRolesFormRules: {
          roleDesc: [ {required: true, message: '请输入角色描述', trigger: 'blur'} ]
        },

        setRightsDialogVisible: false,
        rightslist: [],
        //树形控件的属性绑定对象
        treeProps:{
          label: 'authName',
          children: 'children'
        },
        defKeys: [],
        //当前即将分配权限的id
        roleId: ''

      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      async getRolesList() {
        const {data:res} =await this.$http.get('roles')
        if(res.meta.status !== 200){
          return this.$message.error('获取用户角色失败！')
        }
        this.rolesList = res.data
        //console.log(this.rolesList)
      },
      addRolesDialogClosed() {
        this.$refs.addRolesFormRef.resetFields();
      },
      //添加角色
      addRoles() {
        this.$refs.addRolesFormRef.validate(async valid => {
          //console.log(valid)
          if(!valid) return
          const {data: res} = await this.$http.post('roles',this.addRolesForm)
          if(res.meta.status !== 201){
            this.$message.error('添加角色失败！')
          }
          this.$message.success('添加角色成功！')
          //隐藏对话框
          this.addRolesdialogVisible = false
          //刷新用户列表
          this.getRolesList()
        })
      },
      //根据id查询到角色信息
      async showRolesEditDialog(id){
        //console.log(id)
        this.editRolesDialogVisible = true
        const {data: res} = await this.$http.get('roles/'+id)
        if(res.meta.status !== 200){
          return this.$message.error("查询角色失败！")
        }
        this.editRolesForm = res.data
        this.editRolesDialogVisible = true
      },

      //编辑角色
      editRolesDialogClosed() {
        this.$refs.editRolesFormRef.resetFields();
      },

      editRolesInfo() {
        this.$refs.editRolesFormRef.validate(async valid =>{
          //console.log(valid)
          // if(!valid) return
          //发起网络请求，修改数据
          const {data: res} = await this.$http.put('roles/'+this.editRolesForm.roleId,{
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          })
          if(res.meta.status !== 200){
            return this.$message.error("修改角色失败！")
          }
          this.editRolesDialogVisible = false
          this.getRolesList()
          this.$message.success("修改角色成功！")

        })
      },
      //删除角色
      async removeRolesById(id){
        const confirmRolesResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //如果用户确认删除 返回confirm
        //如果用户取消删除 返回cancle
        //console.log(confirmResult)
        if(confirmRolesResult !== 'confirm'){
          return this.$message.info("已取消删除！")
        }
        const {data: res} = await this.$http.delete('roles/'+ id)
        if(res.meta.status !== 200){
          return this.$message.error("删除用户失败！")
        }
        this.getRolesList()
        this.$message.success("删除用户成功！")

      },
      //根据id删除权限
      async removeRightById(role, rightId) {
        //弹框提示是否删除
        const confirmRolesResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //如果用户确认删除 返回confirm
        //如果用户取消删除 返回cancle
        //console.log(confirmRolesResult)
        if(confirmRolesResult !== 'confirm'){
          return this.$message.info("已取消删除！")
        }
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status !== 200){
          return this.$message.error("删除权限失败！")
        }
        //this.getRolesList()
        role.children = res.data
        this.$message.success("删除权限成功！")
      },
      //分配权限
      async showRightsDialog(role) {
        this.roleId = role.id
        //获取所有权限的数据
        const {data: res} = await this.$http.get('rights/tree')
        if(res.meta.status !== 200){
          return this.$message.error("获取权限数据失败！")
        }
        this.rightslist = res.data
        //递归获取三级权限id
        this.getLeafKeys(role,this.defKeys)
        this.setRightsDialogVisible = true

      },
      //通过递归的形式，获取角色所有的三级权限的id，并保存到defKeys数组中
      getLeafKeys(node, arr) {
        //通过判断是否有children属性来判断是否为三级权限
        if(!node.children){
          return arr.push(node.id)
        }
        node.children.forEach(item =>
          this.getLeafKeys(item, arr))
      },
      //监听分配权限对话框的关闭时间
      setRightsDialogClosed() {
        this.defKeys = [];
      },
      //...为展开运算符
      async allotRight() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        //console.log(keys)
        const idStr = keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
        if(res.meta.status !== 200){
          return this.$message.error("分配权限失败！")
        }
        this.getRolesList()
        this.setRightsDialogVisible = false
        this.$message.success("分配权限成功！")
      },
      setRolesDialogClosed(){
        this.selectedRoleId = ''
        this.userInfo = {}
      }
    }
  }
</script>

<style lang='less' scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
